const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { logOperation } = require('./logs');

// 状态码定义
const CODE = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  NOT_FOUND: 1002,
  SERVER_ERROR: 500,
  NO_PERMISSION: 1003
};

// 获取任务列表
router.get('/lists', async (req, res) => {
  try {
    const { 
      page = 1,           // 当前页码，默认为第1页
      pageSize = 10,      // 每页显示的记录数，默认为10条
      projectId,          // 项目ID，用于过滤特定项目的任务
      moduleId,           // 模块ID，用于过滤特定模块的任务
      status,             // 任务状态，用于按状态过滤任务（如：未开始、进行中、已完成）
      priority,           // 任务优先级，用于按优先级过滤任务（如：低、中、高）
      assigneeId,         // 任务负责人ID，用于查询指定负责人的任务
      creatorId,          // 任务创建人ID，用于查询指定创建人的任务
      sortField = 'created_at',  // 排序字段，默认按创建时间排序
      sortOrder = 'DESC'  // 排序方式，默认降序排列（最新的任务在前）
    } = req.query;

    let conditions = [];
    let params = [];

    if (projectId) {
      conditions.push('t.project_id = ?');
      params.push(projectId);
    }
    if (moduleId) {
      conditions.push('t.module_id = ?');
      params.push(moduleId);
    }
    if (status) {
      conditions.push('t.status = ?');
      params.push(status);
    }
    if (priority) {
      conditions.push('t.priority = ?');
      params.push(priority);
    }
    if (assigneeId) {
      conditions.push('t.assignee_id = ?');
      params.push(assigneeId);
    }
    if (creatorId) {
      conditions.push('t.creator_id = ?');
      params.push(creatorId);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    const orderClause = `ORDER BY t.${sortField} ${sortOrder}`;
    const offset = (page - 1) * pageSize;

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM tasks t ${whereClause}`,
      params
    );
    const total = countResult[0].total;

    // 获取任务列表
    const [tasks] = await pool.execute(
      `SELECT 
        t.id, 
        t.title, 
        t.description, 
        t.project_id, 
        p.name as project_name,
        t.module_id, 
        m.name as module_name,
        t.assignee_id, 
        ua.real_name as assignee_name,
        t.creator_id, 
        uc.real_name as creator_name,
        t.priority, 
        t.status, 
        t.start_date, 
        t.end_date,
        t.estimated_hours,
        t.actual_hours,
        t.created_at,
        t.updated_at
       FROM tasks t
       LEFT JOIN projects p ON t.project_id = p.id
       LEFT JOIN modules m ON t.module_id = m.id
       LEFT JOIN users ua ON t.assignee_id = ua.id
       LEFT JOIN users uc ON t.creator_id = uc.id
       ${whereClause}
       ${orderClause}
       LIMIT ? OFFSET ?`,
      [...params, parseInt(pageSize), offset]
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取任务列表成功',
      data: {
        total,
        list: tasks,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    console.error('获取任务列表错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 获取任务详情
router.get('/details/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const [tasks] = await pool.execute(
      `SELECT 
        t.id, 
        t.title, 
        t.description, 
        t.project_id, 
        p.name as project_name,
        t.module_id, 
        m.name as module_name,
        t.assignee_id, 
        ua.real_name as assignee_name,
        t.creator_id, 
        uc.real_name as creator_name,
        t.priority, 
        t.status, 
        t.start_date, 
        t.end_date,
        t.estimated_hours,
        t.actual_hours,
        t.created_at,
        t.updated_at
       FROM tasks t
       LEFT JOIN projects p ON t.project_id = p.id
       LEFT JOIN modules m ON t.module_id = m.id
       LEFT JOIN users ua ON t.assignee_id = ua.id
       LEFT JOIN users uc ON t.creator_id = uc.id
       WHERE t.id = ?`,
      [id]
    );

    if (tasks.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '任务不存在'
      });
    }

    res.json({
      code: CODE.SUCCESS,
      message: '获取任务详情成功',
      data: tasks[0]
    });
  } catch (error) {
    console.error('获取任务详情错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 创建任务
router.post('/create', async (req, res) => {
  try {
    const {
      projectId,        // 任务所属项目的唯一标识符
      moduleId,         // 项目中特定模块的标识符
      title,            // 任务的简短描述性名称
      description,      // 任务目的和需求的详细说明
      assigneeId,       // 负责完成任务的团队成员ID
      priority = '中',  // 任务重要程度（如：低、中、高、关键）
      status = '未开始', // 任务当前状态（如：未开始、进行中、已完成、已阻塞）
      startDate,        // 任务开始的计划或实际日期
      endDate,          // 任务预期或实际完成日期
      estimatedHours    // 预计完成任务所需时间
    } = req.body;

    
    // 参数校验
    if (!title || !projectId || !assigneeId) {
      return res.json({
        code: CODE.PARAM_ERROR,
        message: '缺少必要参数'
      });
    }

    // 检查项目是否存在
    const [projects] = await pool.execute(
      'SELECT id FROM projects WHERE id = ?',
      [projectId]
    );

    if (projects.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '项目不存在'
      });
    }

    // 如果指定了模块，检查模块是否存在且属于该项目
    if (moduleId) {
      const [modules] = await pool.execute(
        'SELECT id FROM modules WHERE id = ? AND project_id = ?',
        [moduleId, projectId]
      );

      if (modules.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '模块不存在或不属于该项目'
        });
      }
    }

    // 创建任务
    const [result] = await pool.execute(
      `INSERT INTO tasks 
       (project_id, module_id, title, description, assignee_id, creator_id, 
        priority, status, start_date, end_date, estimated_hours, created_at)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())`,
      [
        projectId,
        moduleId || null,
        title,
        description || null,
        assigneeId,
        req.user ? req.user.userId : null,
        priority,
        status,
        startDate || null,
        endDate || null,
        estimatedHours || null
      ]
    );

    // 记录操作日志
    await logOperation(
      // req.user ? req.user.userId : null,
      // 'task_create', 
      // '任务管理', 
      // `创建任务：${title}`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: req.user ? req.user.userId : null,
        type: 'task_create',
        module: '任务管理',
        details: `创建任务：${title}`,
        ipAddress: req.ip,
        userAgent: req.headers['user-agent']
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '创建任务成功',
      data: { 
        id: result.insertId,
        title 
      }
    });
  } catch (error) {
    console.error('创建任务错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 更新任务
router.put('/update/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const {
      projectId,        // 任务所属项目的唯一标识符
      moduleId,         // 项目中特定模块的标识符
      title,            // 任务的简短描述性名称
      description,      // 任务目的和需求的详细说明
      assigneeId,       // 负责完成任务的团队成员ID
      priority,         // 任务重要程度（如：低、中、高、关键）
      status,           // 任务当前状态（如：未开始、进行中、已完成、已阻塞）
      startDate,        // 任务开始的计划或实际日期
      endDate,          // 任务预期或实际完成日期
      estimatedHours,   // 预计完成任务所需时间
      actualHours       // 实际花费在任务上的时间
    } = req.body;

    // 检查任务是否存在
    const [existingTasks] = await pool.execute(
      'SELECT * FROM tasks WHERE id = ?',
      [id]
    );

    if (existingTasks.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '任务不存在'
      });
    }

    // 如果指定了项目，检查项目是否存在
    if (projectId) {
      const [projects] = await pool.execute(
        'SELECT id FROM projects WHERE id = ?',
        [projectId]
      );

      if (projects.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '项目不存在'
        });
      }
    }

    // 如果指定了模块，检查模块是否存在且属于该项目
    if (moduleId) {
      const [modules] = await pool.execute(
        'SELECT id FROM modules WHERE id = ? AND project_id = ?',
        [moduleId, projectId || existingTasks[0].project_id]
      );

      if (modules.length === 0) {
        return res.json({
          code: CODE.NOT_FOUND,
          message: '模块不存在或不属于该项目'
        });
      }
    }

    // 构建更新字段
    const updateFields = [];
    const updateParams = [];

    if (projectId) {
      updateFields.push('project_id = ?');
      updateParams.push(projectId);
    }
    if (moduleId !== undefined) {
      updateFields.push('module_id = ?');
      updateParams.push(moduleId);
    }
    if (title) {
      updateFields.push('title = ?');
      updateParams.push(title);
    }
    if (description !== undefined) {
      updateFields.push('description = ?');
      updateParams.push(description);
    }
    if (assigneeId) {
      updateFields.push('assignee_id = ?');
      updateParams.push(assigneeId);
    }
    if (priority) {
      updateFields.push('priority = ?');
      updateParams.push(priority);
    }
    if (status) {
      updateFields.push('status = ?');
      updateParams.push(status);
    }
    if (startDate !== undefined) {
      updateFields.push('start_date = ?');
      updateParams.push(startDate);
    }
    if (endDate !== undefined) {
      updateFields.push('end_date = ?');
      updateParams.push(endDate);
    }
    if (estimatedHours !== undefined) {
      updateFields.push('estimated_hours = ?');
      updateParams.push(estimatedHours);
    }
    if (actualHours !== undefined) {
      updateFields.push('actual_hours = ?');
      updateParams.push(actualHours);
    }

    // 添加更新时间
    updateFields.push('updated_at = NOW()');
    updateParams.push(id);

    // 执行更新
    await pool.execute(
      `UPDATE tasks SET ${updateFields.join(', ')} WHERE id = ?`,
      updateParams
    );

    // 记录操作日志
    await logOperation(
      // req.user ? req.user.userId : null,
      // 'task_update', 
      // '任务管理', 
      // `更新任务：${id}`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: req.user ? req.user.userId : null,
        type: 'task_update', 
        module: '任务管理', 
        details: `更新任务：${id}`, 
        ipAddress: req.ip || '', 
        userAgent: req.headers['user-agent'] || ''
      }
    );

    // 获取更新后的任务信息
    const [updatedTasks] = await pool.execute(
      `SELECT 
        id, title, project_id, module_id, assignee_id, 
        priority, status, start_date, end_date
       FROM tasks
       WHERE id = ?`,
      [id]
    );

    res.json({
      code: CODE.SUCCESS,
      message: '更新任务成功',
      data: updatedTasks[0]
    });
  } catch (error) {
    console.error('更新任务错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 删除任务
router.delete('/delete', async (req, res) => {
  try {
    const { id } = req.query;

    // 检查任务是否存在
    const [existingTasks] = await pool.execute(
      'SELECT * FROM tasks WHERE id = ?',
      [id]
    );

    if (existingTasks.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '任务不存在'
      });
    }

    // 执行删除
    await pool.execute(
      'DELETE FROM tasks WHERE id = ?',
      [id]
    );

    // 记录操作日志
    await logOperation(
      // req.user ? req.user.userId : null,
      // 'task_delete', 
      // '任务管理', 
      // `删除任务：${id}`, 
      // req.ip || '', 
      // req.headers['user-agent'] || ''
      {
        userId: req.user ? req.user.userId : null,
        type: 'task_delete', 
        module: '任务管理', 
        details: `删除任务：${id}`, 
        ipAddress: req.ip || '', 
        userAgent: req.headers['user-agent'] || ''
      }
    );

    res.json({
      code: CODE.SUCCESS,
      message: '删除任务成功'
    });
  } catch (error) {
    console.error('删除任务错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

module.exports = router;
